package com.longmao.demo.mybatis;

import com.longmao.mapper.LongEmp2Mapper;
import com.longmao.mapper.LongEmpMapper;
import com.longmao.model.LongEmp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by zrb on 17/7/2.
 *
 * sql 使用xml文件
 *
 * 1. 用mybatis-config.xml配置文件,利用SqlSessionFactoryBuilder 生成一个SqlSessionFactory
 * 2. 用于sqlSessionFactory openSession 得到sqlSession
 * 3. sqlSession.getMapper(ClassType)  获得mapper
 * 4. mapper 执行sql 获得结果
 *
 */
public class MybatisAnnotationDemo {


    public static void main(String[] args) {

        //根据mybatis配置获得session
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }


        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获得sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();


        //session 获得mapper, mapper 对应一个表
        LongEmp2Mapper longEmp2Mapper = sqlSession.getMapper(LongEmp2Mapper.class);


        //执行mapper,获得结果
        List<LongEmp> longEmps = longEmp2Mapper.findAll();


        System.out.println("==============================");
        for(LongEmp emp: longEmps){
            System.out.println(emp);
        }
        System.out.println("==============================");

        sqlSession.close();

    }
}
